//
//  GSDKEncryptionHelper.m
//  GameSDK
//
//  Created by Johnny on 2017/7/31.
//  Copyright © 2017年 Johnny. All rights reserved.
//

#import "GSDKEncryptionHelper.h"
#import "GTMBase64.h"
#import "NSData+AES.h"
#import "GSDKComplatformBase.h"
@implementation GSDKEncryptionHelper
//sizeof(key)/sizeof(unichar)取到key中字符的个数，对 i 取余是安全处理，保证 i 在输入字符串长度范围内，c ^= key[]异或位运算加密
+ (NSString *)encryptDecrypt:(NSString *)input {
    unichar key[] = {'G', 'S', 'D', 'K', 'Z', 'Y'};
    NSMutableString *output = [[NSMutableString alloc] init];
    for(int i = 0; i < input.length; i++) {
        unichar c = [input characterAtIndex:i];
        c ^= key[i % sizeof(key)/sizeof(unichar)];
        [output appendString:[NSString stringWithFormat:@"%C", c]];
    }
    return output;
}

+ (NSString *)encryptBase64WithString:(NSString*)encryptString {
    return [GSDKEncryptionHelper encryptAESData:encryptString app_key:[NSString stringWithFormat:@"GSDKZY%@", GSDKINITCONFIGURE.appKey]];
}

+ (NSString *)decodeBase64WithString:(NSString *)decodeString {
    NSData *encryptData = [GTMBase64 decodeString:decodeString];
    return [GSDKEncryptionHelper decryptAESData:encryptData app_key:[NSString stringWithFormat:@"GSDKZY%@", GSDKINITCONFIGURE.appKey]];
}

#pragma mark - AES加密
//将string转成带密码的data
+(NSString*)encryptAESData:(NSString*)string app_key:(NSString*)key {
    //将nsstring转化为nsdata
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    //使用密码对nsdata进行加密
    NSData *encryptedData = [data AES128EncryptWithKey:key];
    //    DEBUGMSG(@"加密后的字符串 :%@",[encryptedData base64Encoding]);
    
    return [encryptedData base64Encoding];
}

#pragma mark - AES解密
//将带密码的data转成string
+(NSString*)decryptAESData:(NSData*)data  app_key:(NSString*)key {
    //使用密码对data进行解密
    NSData *decryData = [data AES128DecryptWithKey:key];
    //将解了密码的nsdata转化为nsstring
    NSString *str = [[NSString alloc] initWithData:decryData encoding:NSUTF8StringEncoding];
    return str;
}

@end
